package com.atjava.nebula.web.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atjava.nebula.core.exception.baseExp.BusinessException;
import com.atjava.nebula.core.exception.baseExp.SystemException;
import com.atjava.nebula.core.service.GenericService;
import com.atjava.nebula.core.util.entity.EntitySupport;
import com.atjava.nebula.frames.user.SysUser;

@Controller
@RequestMapping("/system/user")
public class UserAction extends BaseViewAction{

	@RequestMapping(value="/edit",method = RequestMethod.POST)
	@ResponseBody
	public SysUser editUser(HttpServletRequest request,
			@RequestParam(REQ_PARAM_QUERYPK) String pkstr,
			ModelMap modelMap) throws SystemException, BusinessException{
		
		SysUser model = (SysUser) getModelFromRequest(SysUser.class, request);
		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		
		
		GenericService<SysUser,String> userService = getService(SysUser.class, String.class);
		
		//update
		if(StringUtils.isNotBlank(pkstr)){
			
			EntitySupport.setPkToEntity(SysUser.class, model ,pkstr);
			
			//should after setpktoentity method,
			model.setPassword(encoder.encodePassword(model.getPassword(), model.getUserId()));
			
			userService.updateAllById(model);
			
		//add
		}else{
			model.setPassword(encoder.encodePassword(model.getPassword(), model.getUserId()));
			userService.create(model);
		}
		
		return model;
	}
	
}
